package main

import (
	"fmt"
	"net"
	"runtime"
	"sync/atomic"
	"time"
)

var client_map = make(map[string]*net.TCPAddr)

/*
func listen_client(ip_port string) {
	tcpAddr, _ := net.ResolveTCPAddr("tcp", ip_port)
	tcpListener, _ := net.ListenTCP("tcp", tcpAddr)
	for {
		client_con, _ := tcpListener.AcceptTCP()
		client_map[client_con.RemoteAddr().String()] = client_con
		go add_receiver(client_con)
		fmt.Println("user:", client_con.RemoteAddr().String(), "linked")
	}
}
*/
func add_receiver(current_connect *net.TCPConn) {
	byte_msg := make([]byte, 2048)

	len, err := current_connect.Read(byte_msg)
	if err != nil {
		current_connect.Close()
	}
	fmt.Println(string(byte_msg[:len]))

}

func chanelstep() {
	messages := make(chan string, 2)

	messages <- "buffered"
	messages <- "channel"

	fmt.Println("get message1:", <-messages)
	fmt.Println("get message2:", <-messages)
}

func worker(done chan bool) {
	fmt.Println("start working...")
	time.Sleep(time.Second * 2)
	fmt.Println("done...")
	done <- true
}

func channelTest() {
	done := make(chan bool, 1)
	go worker(done)

	<-done
}

func workerT(id int, jobs <-chan int, results chan<- int) {
	for j := range jobs {
		fmt.Println("worker", id, "processing job", j)
		time.Sleep(time.Second)
		results <- j * 2
	}
}

func jobs() {
	jobs := make(chan int, 100)
	results := make(chan int, 100)

	for w := 1; w <= 3; w++ {
		go workerT(w, jobs, results)
	}

	for j := 1; j <= 9; j++ {
		jobs <- j
	}
	close(jobs)

	for a := 1; a <= 9; a++ {
		<-results
	}
}

func ato() {
	var opt uint64 = 0

	for i := 0; i < 50; i++ {
		go func() {
			atomic.AddUint64(&opt, 1)
			runtime.Gosched()
		}()
	}

	time.Sleep(time.Second)
	opsf := atomic.LoadUint64(&opt)
	fmt.Println("ops:", opsf)

}

func main() {
	fmt.Println("server start...")
	time.Sleep(1 * time.Second)
	fmt.Println("waiting client...")
	// go listen_client("127.0.0.1:1801")
	// select {}
	chanelstep()
	channelTest()
	jobs()
	ato()
}
